#!/usr/bin/bash
set -e

# 获取安装版本
echo -n "install kafka version(3.5.1): "
read version

download_path="https://mirrors.tuna.tsinghua.edu.cn/apache/kafka/${version}/kafka_2.13-${version}.tgz"
binary_name=`basename ${download_path}`

package_dir="/srv/package/"
install_dir="/srv/software/"
custom_env_file="/etc/profile.d/custom_env.sh"

# 创建存放目录，然后下载、安装、改名
mkdir -p ${package_dir} ${install_dir}
wget ${download_path} -P ${package_dir}
tar xf ${package_dir}${binary_name} -C ${install_dir}

# 添加环境变量
software_name=$(ls -l ${install_dir} |grep kafka |grep ${version} |awk '{print $9}')
software_home=${install_dir}${software_name}
cat >> ${custom_env_file} <<-EOF
export KAFKA_HOME=${software_home}
export PATH=\$KAFKA_HOME/bin:\$PATH
EOF
source /etc/profile


# 修改 server.properties 内容
sed -i '{
s#controller.quorum.voters=1@localhost:9093#controller.quorum.voters=1@node1:9093,2@node2:9093,3@node3:9093#
s#advertised.listeners=PLAINTEXT://localhost:9092#advertised.listeners=PLAINTEXT://node1:9092#
s#log.dirs=/tmp/kraft-combined-logs#log.dirs=\${software_home}/data#
}' ${software_home}/config/kraft/server.properties

# 修改 server.properties 内容
sed -i "{
s#log.dirs=\${software_home}/data#log.dirs=${software_home}/data#
}" ${software_home}/config/kraft/server.properties

# 分发配置，并修改值
scp -r ${software_home} node2:${install_dir}
scp -r ${software_home} node3:${install_dir}

scp ${custom_env_file} node2:${custom_env_file}
scp ${custom_env_file} node3:${custom_env_file}

ssh root@node2 "sed -i 's#advertised.listeners=PLAINTEXT://node1:9092#advertised.listeners=PLAINTEXT://node2:9092#' ${software_home}/config/kraft/server.properties"
ssh root@node2 "sed -i 's#node.id=1#node.id=2#' ${software_home}/config/kraft/server.properties"
ssh root@node3 "sed -i 's#advertised.listeners=PLAINTEXT://node1:9092#advertised.listeners=PLAINTEXT://node3:9092#' ${software_home}/config/kraft/server.properties"
ssh root@node3 "sed -i 's#node.id=1#node.id=3#' ${software_home}/config/kraft/server.properties"

# 群起脚本
cat > /usr/local/bin/kafka-daemon.sh <<EOF
#!/bin/bash
for host in node1 node2 node3
do
    case \$1 in
    "start")
        echo "===== \$host kafka \$1 ====="
        ssh \$host "source /etc/profile;\${KAFKA_HOME}/bin/kafka-server-start.sh -daemon \${KAFKA_HOME}/config/kraft/server.properties"
    ;;
    "stop")
        echo "===== \$host kafka \$1 ====="
        ssh \$host "source /etc/profile;\${KAFKA_HOME}/bin/kafka-server-stop.sh"
    ;;
    esac
done
EOF
chmod 755 /usr/local/bin/kafka-daemon.sh

# 安装成功提示
echo "Successfully installed kafka..."